package com.ptswitch.material.web.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;

import com.ptswitch.material.model.Material;
import com.ptswitch.material.model.Upload;
import com.ptswitch.material.util.Constant;

@Controller("materialUploadAction")
public class MaterialUploadAction extends UploadAction {

	private List<Material> dbMaterials = new ArrayList<Material>();
	private List<Material> updateMaterials = new ArrayList<Material>();
	private List<Material> newMaterials = new ArrayList<Material>();

	// upload
	public String upload() {
		mustAdmins();
		uploads();
		for (Upload upload : uploads) {
			upload.setOwnerType(ownType);
			upload.setOwnerId(ownId);
			uploadSer.save(upload);
			hlogSer.log(visitor(), Constant.addUpload, upload.getFileName());
		}
		return "display";
	}

	public String delete() {
		mustAdmins();
		upload = uploadSer.get(id);
		FileUtils.deleteQuietly(new File(ActionSupport.getSavePath() + upload.getFilePath()));
		uploadSer.delete(upload);
		hlogSer.log(visitor(), Constant.deleteUpload, upload.getFileName());
		id = upload.getOwnerId();
		return "display";
	}

	// import
	public String toImportMaterial() {
		mustAdmins();
		return "import";
	}

	public String importMaterial() {
		mustAdmins();
		uploads();
		if (uploads.isEmpty()) {
			return "import";
		}
		List<Material> materials = new ArrayList<Material>();
		Upload upload = uploads.get(0);
		try {
			excelSer.read(ActionSupport.getSavePath(), upload.getFilePath());
			excelSer.buildMaterialsFromExcel(materials);
		} catch (Exception e) {
			FileUtils.deleteQuietly(new File(ActionSupport.getSavePath() + upload.getFilePath()));
			putMsg("读取物料表文件错误：" + e.getMessage());
			return "import";
		}
		// unique check
		Map<String, Material> map = new HashMap<String, Material>();
		Set<String> codelist = new HashSet<String>();
		List<Material> list = new ArrayList<Material>();
		for (Material material : materials) {
			if (map.containsKey(material.getCode())) {
				codelist.add(material.getCode());
				list.add(material);
			} else {
				map.put(material.getCode(), material);
			}
		}
		for (String code : codelist) {
			list.add(map.get(code));
		}
		if (!list.isEmpty()) {
			Collections.sort(list);
			display.put("duplicated", list);
			FileUtils.deleteQuietly(new File(ActionSupport.getSavePath() + upload.getFilePath()));
			putMsg("导入物料表错误：物料表中含有以下重复数据");
			return "duplicated";
		}
		// db check
		dbMaterials.clear();
		updateMaterials.clear();
		newMaterials.clear();
		Material dbMaterial;
		for (Material material : materials) {
			dbMaterial = materialSer.getByCode(material.getCode());
			if (dbMaterial != null) {
				dbMaterials.add(dbMaterial);
				updateMaterials.add(material);
			} else {
				newMaterials.add(material);
			}
		}
		// only add new
		try {
			materialSer.saveAll(newMaterials);
		} catch (Throwable e) {
			if (e instanceof DataAccessException) {
				e = e.getCause().getCause();
			}
			putMsg("导入物料表错误：" + e.getMessage());
			logger.error("import bom error", e);
			return "import";
		}
		hlogSer.log(visitor(), Constant.addListMaterial);
		// display
		display.put("newMaterials", newMaterials);
		if(dbMaterials.isEmpty()){
			putMsg("新增物料" + newMaterials.size() + "个");
			return "list";
		}
		display.put("dbMaterials", dbMaterials);
		display.put("updateMaterials", updateMaterials);
		putMsg("更新物料" + updateMaterials.size() + "个，新增物料" + newMaterials.size() + "个");
		return "overwrite";
	}

	public String importUpdates() {
		mustAdmins();
		try {
			materialSer.deleteAll(dbMaterials);
			materialSer.saveAll(updateMaterials);
		} catch (Throwable e) {
			if (e instanceof DataAccessException) {
				e = e.getCause().getCause();
			}
			putMsg("导入物料表错误：" + e.getMessage());
			logger.error("import bom error", e);
			return "import";
		}
		// for(Material material:newMaterials){
		// materialSer.save(material);
		// }
		hlogSer.log(visitor(), Constant.updateListMaterial);
		return "list";
	}

	// output
	public String exportMaterial() {
		List<Material> materials = materialSer.getAll();
		excelSer.outputMaterials(materials);
		String outFilePath = ActionSupport.getSavePath() + "output/materials.xls";
		excelSer.write(outFilePath);
		this.upload = new Upload();
		this.upload.setFilePath("output/materials.xls");
		this.upload.setFileName("materials.xls");
		this.upload.setFileType("application/vnd.ms-excel");
		return "download";
	}

	// get and set

}
